package io.gitee.twoke.generator.engine.impl.generate.processor;

import io.gitee.twoke.generator.engine.GenerateEngine;
import io.gitee.twoke.generator.engine.GenerateEngines;
import io.gitee.twoke.generator.engine.GenerateService;
import io.gitee.twoke.generator.engine.TemplateService;
import io.gitee.twoke.generator.engine.impl.*;
import io.gitee.twoke.generator.engine.impl.cfg.GenerateEngineConfigurationImpl;
import io.gitee.twoke.generator.engine.impl.generate.parameter.ParameterContext;
import io.gitee.twoke.generator.engine.impl.generate.parameter.ParameterLoaderManager;
import io.gitee.twoke.generator.engine.impl.template.TemplateFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenerateExecutorImpl extends AbstractGenerateProcessorExecutor{

    public static final String TABLE_NAME = "tableName";
    public static final String DATA = "data";
    public static final String FIELDS = "fields";

    private GenerateEngineConfigurationImpl generateEngineConfiguration;
    private GenerateEngine generateEngine;
    private TemplateGenerator templateGenerator;
    private ParameterLoaderManager parameterLoaderManager;

    public GenerateExecutorImpl(GenerateEngineConfigurationImpl generateEngineConfiguration) {
        this.generateEngineConfiguration = generateEngineConfiguration;
        this.parameterLoaderManager = generateEngineConfiguration.getParameterLoaderManager();
        this.generateEngine = GenerateEngines.getGenerateEngine(generateEngineConfiguration.getGenerateEngineName());
        this.templateGenerator = new SimpleTemplateGenerator(generateEngineConfiguration.getVelocityEngine(), generateEngineConfiguration.getOutputExecutor());
    }

    @Override
    protected void invokeProcess(GenerateProcessContext context) {
        List<TemplateFile> templateFiles = context.getTemplateFiles();
        ParameterContext parameterContext = parameterLoaderManager.createContext(
                new HashMap<String, Object>(){{
                    put(DATA, context.getTableConfig());
                    put(FIELDS, context.getTableConfig().getColumns());
                    put(TABLE_NAME, context.getTableConfig().getTableName());
                }}
        );
        templateGenerator.generate(GenerateContext.builder()
                        .templates(templateFiles)
                        .context(parameterContext.getContext())
                        .outputDir(context.getTableConfig().getGeneratePath())
                        .outputType(context.getTableConfig().getGenerateType())
                .build());
    }

    @Override
    protected TemplateService getTemplateService() {
        return this.generateEngine.getTemplateService();
    }

    @Override
    protected GenerateService getGenerateService() {
        return this.generateEngine.getGenerateService();
    }


}
